#!/usr/bin/env python
# coding: utf-8
from engine.person import *
from engine.common import *
from baidu.aips import *
class taskItem:
    """taskItem"""
    nid = 0
    taskItemName = ""
    currentScreen = ""
    exceptScreen = ""
    errorStatusNo = ""
    beforeCalcCommond = ""#需要计算 用户自定义函数
    beforeCalcResult  = ""#自定义函数计算结果参数 传递
    afterCalcCommond = ""#需要计算 用户自定义函数
    afterCalcResult  = ""#自定义函数计算结果参数 传递
    actionCommand = "" #执行指令 例如  click  keyevent  或者 用户自定义 函数
    innerStatus = "ready" # ready before  action after done 五种 顺序执行
    innerError = 0

    def __init__(self):
        self.innerStatus = "ready"
        self.innerError = 0
        self.taskItemName = ""
        self.currentScreen = ""
        self.exceptScreen = ""
        self.errorStatusNo = ""
        self.beforeCalcCommond = ""#需要计算 用户自定义函数
        self.beforeCalcResult  = ""#自定义函数计算结果参数 传递
        self.afterCalcCommond = ""#需要计算 用户自定义函数
        self.afterCalcResult  = ""#自定义函数计算结果参数 传递
        self.actionCommand = "" #执行指令 例如  click  keyevent  或者 用户自定义 函数
    def __init__(self,nid):
        self.nid = nid
        self.innerStatus = "ready"
        self.innerError = 0
        self.taskItemName = ""
        self.currentScreen = ""
        self.exceptScreen = ""
        self.errorStatusNo = ""
        self.beforeCalcCommond = ""#需要计算 用户自定义函数
        self.beforeCalcResult  = ""#自定义函数计算结果参数 传递
        self.afterCalcCommond = ""#需要计算 用户自定义函数
        self.afterCalcResult  = ""#自定义函数计算结果参数 传递
        self.actionCommand = "" #执行指令 例如  click  keyevent  或者 用户自定义 函数
    def setJumpError(self):
        print("jumper--nid--" + str(self.nid)+"     jumper--errorStatusNo--:"+self.errorStatusNo)
        self.innerStatus = 'done'
        if '-' in self.errorStatusNo or '+' in self.errorStatusNo:
            jump = eval(self.errorStatusNo)
            #print(jump)
            self.innerError = str(self.nid + jump)
        else:
            self.innerError = self.errorStatusNo
        #print("innerError--nid--" + (self.innerError))
        return self.innerError

    def itemStatusUpdate(self,currentScreen):
        print(str(self.nid)+self.taskItemName)

        ret = "None"
        if 'after' in self.innerStatus:
            print("(4)status form after to done  no need calc-------"+self.afterCalcCommond)
            if 'delay' in self.afterCalcCommond:
                delaySec = self.afterCalcCommond.split('*')
                print("run after delay  for seconds"+str(delaySec[1]))
                time.sleep(int(delaySec[1]))


            #保存期待界面 ./shouji/nokiax5/screen 目录下创建 对应文件夹 并按时间保存  期待界面
            if not 'None' in(self.exceptScreen):
                if len(self.exceptScreen)>1:
                    print("有要备份的 cp current to 期待界面描述")
                    #判断目录
                    if not os.path.exists(os.getcwd()+"/shouji/"+currentScreen.type+"/"):
                        os.mkdir(os.getcwd()+"/shouji/"+currentScreen.type+"/")
                    if not os.path.exists(os.getcwd()+"/shouji/"+currentScreen.type+"/screen/"):
                        os.mkdir(os.getcwd()+"/shouji/"+currentScreen.type+"/screen/")
                    if not os.path.exists(os.getcwd()+"/shouji/"+currentScreen.type+"/screen/"+self.exceptScreen):
                        os.mkdir(os.getcwd()+"/shouji/"+currentScreen.type+"/screen/"+self.exceptScreen)
                    try:
                        fname = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                        fname = fname+"e.png"
                        copyfile(currentScreen.currentScreen,os.getcwd()+"/shouji/"+currentScreen.type+"/screen/"+self.exceptScreen+"/"+fname)

                    except:
                        pass
            #TODO:判断之前界面属性， 也就是事后界面 是不是事后界面所描述的内容 如果符合继续，啥都不做 如果不符合看情况是不是要结束任务或设置 innnerError
            ###############################################################
            #事后的判断 代码执行 未完成  例如 except图片的内容 给判断下 不属于 xxxx 则 执行 ret = errorStatusNo 就会跳转到对应的代码   最好要删除 刚才备份的那张
            #也可以 直接设置 innerError 内部错误 不为0  下面的自动跳转了
            #ret = self.errorStatusNo   #just a test code for test error jump code
            ###############################################################
            if  not 'None' in self.afterCalcCommond and not 'delay' in self.afterCalcCommond:
                #time.sleep(1)

                if self.afterCalcCommond.startswith('out*'):
                    print("外部程序运行 需要调用")
                    currentScreen.getCurrentScreen(str(self.nid)+self.taskItemName+"after recogScreen")
                    setErrorCountZero()
                    recogScreen(currentScreen.currentScreen)
                    setErrorCountZero()

                    retTemp = self.afterCalcCommond.split('*')
                    # command 为  ret[1]
                    # 运行文件  self.taskItemName  目录下 的 taskItemName  py 文件 参数1 handset 2 sno 3.  ret1 4.ret2
                    outFile = os.getcwd()+"/shouji/" + getHandsetType() + "/taskCommon/" + self.taskItemName + "/" + self.taskItemName + ".py "
                    cmd = getOutFileCmd(outFile)
                    count = 0
                    for para in retTemp:
                        print('分割参数')
                        print(para)
                        if count < 1:
                            pass
                        else:
                            cmd = cmd + para + " "
                        count = count + 1
                    print(cmd)
                    os.system(cmd)
                else:
                    if 'stateChange' in self.afterCalcCommond:
                        ret = self.setJumpError()

                #TODO：事后计算在这里 判断 事后计算属性是否 None 如果不是 则调用相关代码
                if  not 'None' in self.afterCalcResult:
                    print(os.getcwd())
                    with open(getHandsetFileSavePath(self.afterCalcResult)) as f:
                        stateChange = f.read()
                    if 'True' in stateChange:
                        ret = self.setJumpError()
                        debugInfo("发生状态转化了 -----跳转到其他状态---------------------------")
                        #time.sleep(10)
            currentScreen.getCurrentScreen(str(self.nid) + self.taskItemName + "after")
            if  'compareImage' in self.afterCalcCommond:

                isSame,conf = isSameScreen(str(self.nid)+self.taskItemName+".png",str(self.nid)+self.taskItemName+"after.png")
                if (isSame):
                    print("对比事前后图像是同一个")
                else:
                    print("图像不同")

                if isSame == False and 'compareImageNotSameJump' in self.afterCalcCommond:
                    print("compareImageNotSameJump happend")
                    ret = self.setJumpError()
                if isSame == True and 'compareImageSameJump' in self.afterCalcCommond:
                    print("compareImageSameJump happend")
                    ret = self.setJumpError()


            self.innerStatus = 'done'
            os.system("rm "+getHandsetFileSavePath("/temp/")+"pos*.txt")
            #os.system("rm " + getHandsetFileSavePath("/temp/") + "desc.txt")
            #os.system("rm " + getHandsetFileSavePath("/temp/") + "tkl.txt")
            pass
        if 'action' in self.innerStatus:
            print("(3)run action  now -----------------"+self.actionCommand)
            if self.actionCommand.startswith('out*'):
                print("外部程序运行 需要调用")
                ret = self.actionCommand.split('*')
                #command 为  ret[1]
                #运行文件  self.taskItemName  目录下 的 taskItemName  py 文件 参数1 handset 2 sno 3.  ret1 4.ret2
                outFile = os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/"+self.taskItemName+".py "
                cmd = getOutFileCmd(outFile)
                count = 0
                for para in ret:
                    print('分割参数')
                    print(para)
                    if count<1:
                        pass
                    else:
                        cmd = cmd + para +" "
                    count = count +1
                os.system(cmd)
            if "KEYCODE_" in self.actionCommand:
                print('执行快捷键盘操作')
                adbRun("  shell input keyevent "+self.actionCommand)
            if 1:#"study" in self.errorStatusNo:

                if 'swipeLeftToRight' in self.actionCommand:
                    swipeLeftToRight()
                if 'swipeRightToLeft' in self.actionCommand:
                    swipeRightToLeft()
                if 'swipeScreen' in self.actionCommand:
                    swipePlist = self.actionCommand.split("*")
                    touchSwipeScreen(swipePlist[1],swipePlist[2],swipePlist[3],swipePlist[4],swipePlist[5])

                #TODO tap or longtap or keysend
                if "inputABC" in self.actionCommand:
                    ret = self.actionCommand.split("*")
                    inputABC(ret[1])
                    #touchLongpress
                if "touchTap" in self.actionCommand or 'touchLongpress' in self.actionCommand:
                    print("单点击任务")
                    #判断当面目录有没有 posx.txt posy.txt
                    #解析是前结果
                    poscontentx=0
                    poscontenty=0
                    if '*' in self.beforeCalcResult:
                        poscontent= self.beforeCalcResult.split('*')[0]
                        if len(poscontent.split(',')[0].replace('posx',''))>1:
                            poscontentx = int(poscontent.split(',')[0].replace('posx',''))
                        if len(poscontent.split(',')[1].replace('posy','')) > 1:
                            poscontenty = int( poscontent.split(',')[1].replace('posy',''))
                    print('offsetx = '+str(poscontentx))
                    print('offsety = '+str(poscontenty))
                    found = False
                    if os.path.exists(getHandsetFileSavePath("/temp/posx.txt")) and os.path.exists(getHandsetFileSavePath("/temp/posy.txt")):
                        print("点击这两个点")
                        found = True
                        with open(getHandsetFileSavePath("/temp/posx.txt") )as f:
                            xx = f.read().strip()
                        with open(getHandsetFileSavePath("/temp/posy.txt") )as f:
                            yy = f.read().strip()
                    elif  not 'NoFoundNoAction' in self.actionCommand:
                        if os.path.exists(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/posx.txt") and os.path.exists(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/posy.txt"):
                            with open(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/posx.txt" )as f:
                                xx = f.read().strip()
                            with open(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/posy.txt" )as f:
                                yy = f.read().strip()

                    if found == True:
                        if 'touchLongpress' in self.actionCommand:
                            touchLongpress(int(int(float(xx)) + poscontentx), int(int(float(yy)) + poscontenty))
                        elif  'touchTap' in self.actionCommand:
                            touchTap(int(int(float(xx)) + poscontentx), int(int(float(yy)) + poscontenty))
                    else:
                        print("not found call ed")
                        if  'NoFoundNoAction' in self.actionCommand:
                            print("NoFoundNoAction called------------")


                            ret = self.setJumpError()

                            #time.sleep(20)
                        else:#use common data for tap

                            try:
                                if 'touchLongpress' in self.actionCommand:
                                    touchLongpress(int(int(float(xx)) + poscontentx), int(int(float(yy)) + poscontenty))
                                elif 'touchTap' in self.actionCommand:
                                    touchTap(int(int(float(xx)) + poscontentx), int(int(float(yy)) + poscontenty))
                            except:
                                print("error recoge get posx posy----------")
                                pass


                            pass #just comment it now




                if 'setCliper' in self.actionCommand:
                    print("设置剪贴板的任务")
                    content = self.actionCommand.split("*")[1]
                    #如果setCliper 后面跟点是路径 那么打开文件读出来，如果是内容 直接设置
                    if '/' in content and os.path.exists(getHandsetFileSavePath(content)):
                        pathtemp = getHandsetFileSavePath(content)
                        with open(pathtemp) as f:
                            content = f.read()
                            content=content.replace(" ","[s]")
                            content = content.replace("\n", "[nr]")
                        getAndSetMsgFromHandsetCliper(content,getHandsetSno())
                    else:
                        getAndSetMsgFromHandsetCliper(content,getHandsetSno())
                    print("剪贴板设置了--："+content)
                    if '(test)' in content or 'tkl' in content or "准备好了接受指令了" in content:
                        ret = self.setJumpError()
            if 'action' in self.innerStatus:
                self.innerStatus = 'after'
            pass
        if 'before' in self.innerStatus:
            print("(2)run before calc now ----------"+self.beforeCalcCommond)
            if self.beforeCalcCommond.startswith('out*'):
                print("外部程序运行 需要调用")
                ret = self.beforeCalcCommond.split('*')
                # command 为  ret[1]
                # 运行文件  self.taskItemName  目录下 的 taskItemName  py 文件 参数1 handset 2 sno 3.  ret1 4.ret2
                outFile = os.getcwd() + "/shouji/" + getHandsetType() + "/taskCommon/" + self.taskItemName + "/" + self.taskItemName + ".py "
                cmd = getOutFileCmd(outFile)
                count = 0
                for para in ret:
                    print('分割参数')
                    print(para)
                    if count < 1:
                        pass
                    else:
                        cmd = cmd + para + " "
                    count = count + 1
                os.system(cmd)
                # TODO：事后计算在这里 判断 事后计算属性是否 None 如果不是 则调用相关代码
                if not 'None' in self.beforeCalcResult:
                    #print(os.getcwd())
                    with open(getHandsetFileSavePath(self.beforeCalcResult)) as f:
                        stateChange = f.read()
                    if 'True' in stateChange:
                        ret = self.setJumpError()
                        debugInfo("发生状态转化了 --------------------------------")
                        #time.sleep(10)

            else:
                if "study" in self.errorStatusNo:

                    print(getWhatScreen(currentScreen.currentScreen))
                    print("现在是学习时间 现在是学习："+self.taskItemName)
                    print("兴趣点："+self.beforeCalcCommond)
                    print("需要您点击一下 ，并在之后提示里面输入 宽度高度，祝您学习愉快")
                    if not os.path.exists(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName):
                        os.mkdir(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName)
                        print("创建目录文件"+os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName)
                    else:
                        print("注意学习的目录文件已经存在，会覆盖掉哦"+os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName)

                    x,y = getTouchPos()
                    ret  = getTouchPosRect(currentScreen.currentScreen,x,y,os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/"+self.beforeCalcCommond+".png")
                    #x,y写入文件
                    #如果存在对应的文件夹 例如  shouji nokiax5 taskCommon 下 任务名称  就写入 xy

                    if ret == 0:#上面跳过学习了
                        print("看了本页面您已经学习好了")
                        pass
                    elif ret ==2:
                        self.innerStatus = "ready"
                    else:
                        with open(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/posx.txt","w") as f:
                            f.write(str(x))
                        with open(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/posy.txt","w") as f:
                            f.write(str(y))
                    print("study mode now-----------------")
                else:
                    #TODO invoke the before calc process 计算 新的坐标点  保存到posx posy temp的目录
                    posx = -1
                    posy = -1
                    if not 'None' in self.beforeCalcCommond and os.path.exists(os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/"+self.beforeCalcCommond+".png") :
                        con = 0.99
                        if "*" in self.beforeCalcResult:
                            con = float(self.beforeCalcResult.split('*')[1])
                        print("confience = "+str(con))
                        if 'MinY' in self.beforeCalcCommond:
                            posx, posy = matchImgMinY(currentScreen.currentScreen,
                                                  os.getcwd()+"/shouji/" + getHandsetType() + "/taskCommon/" + self.taskItemName + "/" + self.beforeCalcCommond + ".png",
                                                  con)
                        elif 'MaxY' in self.beforeCalcCommond:
                            posx, posy = matchImgMaxY(currentScreen.currentScreen,
                                                      os.getcwd()+"/shouji/" + getHandsetType() + "/taskCommon/" + self.taskItemName + "/" + self.beforeCalcCommond + ".png",
                                                      con)
                            pass
                        elif 'MinY2' in self.beforeCalcCommond:
                            posx, posy = matchImgMinY2(currentScreen.currentScreen,
                                                      os.getcwd()+"/shouji/" + getHandsetType() + "/taskCommon/" + self.taskItemName + "/" + self.beforeCalcCommond + ".png",
                                                      con)
                        else:
                            posx,posy = matchImg(currentScreen.currentScreen,os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/"+self.beforeCalcCommond+".png",con)
                        print("calc posx =="+str(posx))
                        print("calc posy =="+str(posy))
                        print("\noldx ====")
                        os.system("cat "+os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/posx.txt")
                        print("\noldy===")
                        os.system("cat "+os.getcwd()+"/shouji/"+getHandsetType()+"/taskCommon/"+self.taskItemName+"/posy.txt")
                    elif not 'None' in self.beforeCalcCommond  and not "Local"in self.beforeCalcCommond and "posx" in self.beforeCalcResult:
                        #recorg this screen get posx posy by  beforeCalcCommand content
                        posx,posy = baiduAip(currentScreen.currentScreen,self.beforeCalcCommond)
                        pass
                    elif   "Local"in self.beforeCalcCommond and "posx" in self.beforeCalcResult:
                        posx = 0
                        posy = 0
                        keywords = self.beforeCalcCommond.split("*")
                        for keyF in keywords:
                            #recorg this screen get posx posy by  beforeCalcCommand content
                            temp = keyF.replace("Local","")
                            print(temp)

                            #设置第几次出现的 兴趣点 是所要的 默认1  Local 信息（2） 就是第2
                            numberx = 1
                            if "(" in temp and ")" in temp:
                                temp1 = temp.split("(")[0]
                                temp2 = temp.split("(")[1]
                                temp2 = temp2.split(")")[0]
                                temp = temp1
                                numberx = int(temp2)


                            setErrorCountZero()
                            tempList = recogScreen(currentScreen.currentScreen)
                            setErrorCountZero()
                            if len(tempList)<1:
                                posx, posy = baiduAip(currentScreen.currentScreen, temp)
                            else:
                                countx = 0
                                for list in tempList:
                                    #print(list)
                                    if temp in list[1]:
                                        countx = countx +1
                                        if countx == numberx:
                                            print("发现目标文字及坐标 --- "+temp)
                                            posy = int(list[0][1] + list[0][3] / 2)
                                            posx = int(list[0][0] + list[0][2] / 2)
                                            print(posx)
                                            print(posy)
                                            break
                            if not posx == 0 and not posy == 0:
                                break




                        pass
                    if posx>0 and posy>0:
                        print("save new posxy  newfile create in temp dir   /temp/posx.txt")
                        with open(getHandsetFileSavePath("/temp/posx.txt"),'w')as f:
                            f.write(str(posx))
                        with open(getHandsetFileSavePath("/temp/posy.txt"),'w')as f:
                            f.write(str(posy))
                        if 'FoundChange' in self.beforeCalcResult:
                            ret = self.setJumpError()

                    elif posx == -2 and posy==-2:
                        self.innerStatus = "ready"
                    else:
                        print("忽略计算，使用系统之前的 pos")
                        with open(getHandsetFileSavePath("/temp/posx_error.txt"), 'w')as f:
                            f.write(str(posx))
                        with open(getHandsetFileSavePath("/temp/posy_error.txt"), 'w')as f:
                            f.write(str(posy))
                        if   'FoundNotChange' in  self.beforeCalcResult:

                            ret = self.setJumpError()
                    pass


            if 'before' in self.innerStatus:
                self.innerStatus = 'action'
            pass
        if 'ready' in  self.innerStatus:
            wakeupHandset()
            debugInfo("开始任务中的"+self.taskItemName)
            #ready to before canbe run now
            print("(1)from ready to  run before now 当前 屏幕可能是下面的内容------------------------------")
            # print(getWhatScreen(currentScreen.currentScreen))
            #保存之前当前页面为之前页面  ./shouji/nokiax5/screen 目录下创建 对应文件夹 并按时间保存  之前界面
            if not 'None' in(self.currentScreen):
                if len(self.currentScreen)>1:
                    print("有要备份的 cp current to 之前界面描述")
                    #判断目录
                    if not os.path.exists(os.getcwd()+"/shouji/"+currentScreen.type+"/"):
                        os.mkdir(os.getcwd()+"/shouji/"+currentScreen.type+"/")
                    if not os.path.exists(os.getcwd()+"/shouji/"+currentScreen.type+"/screen/"):
                        os.mkdir(os.getcwd()+"/shouji/"+currentScreen.type+"/screen/")
                    if not os.path.exists(os.getcwd()+"/shouji/"+currentScreen.type+"/screen/"+self.currentScreen):
                        os.mkdir(os.getcwd()+"/shouji/"+currentScreen.type+"/screen/"+self.currentScreen)
                    try:
                        fname = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                        fname = fname+"c.png"
                        copyfile(currentScreen.currentScreen,os.getcwd()+"/shouji/"+currentScreen.type+"/screen/"+self.currentScreen+"/"+fname)
                    except:
                        pass
            if '启动' in self.taskItemName:
                print("ready this is a  启动 task then start this task"+self.taskItemName)
                #actioncommand 设置为 默认delay时间 如果没有设置 则默认
                if self.actionCommand.isdigit():
                    launchApp(self.taskItemName,int(self.actionCommand))
                else:
                    launchApp(self.taskItemName)

            #TODO:判断之前界面属性， 也就是当前界面 是不是之前界面所描述的内容 如果符合继续，啥都不做 如果不符合看情况是不是要结束任务或设置 innnerError
            currentScreen.getCurrentScreen(str(self.nid)+self.taskItemName)
            #whatSc = getWhatScreen(currentScreen.currentScreen)
            # print("当前界面名："+self.currentScreen)
            # print("识别的界面名："+whatSc)
            #debugInfo("当前界面"+self.currentScreen+"[nr]"+"识别界面"+whatSc)
            # if self.currentScreen in whatSc:
            #     print("相同啊，good job")
            # else:
            #     print("TODO: 不相同，需要做点什么吗！！！！！！！！！！！！！！！！goodgoodstudydaydayup！！！！！！！！！！！！！！！！！！")


            #run code for  before
            self.innerStatus = 'before'

        return ret,self.innerStatus



